//EZblu 主客服
import React, { useState,useEffect } from 'react'
import {InputItem,Button} from "antd-mobile"
import {
    PieChartOutlined,
  } from '@ant-design/icons';
import GoEasy from 'goeasy'
import { Menu,Input} from 'antd';
//import axios from 'axios'
import Header from '../assets/img/katong.png'
import Kehu from '../assets/img/110.png'
const { SubMenu } = Menu;
const { TextArea } = Input;

var goeasy  = GoEasy.getInstance({
    host:"singapore.goeasy.io",  //若是新加坡东南亚区域：singapore.goeasy.io // 中国区域hangzhou.goeasy.io
    appkey:"BC-61f166d35a9a4283a65a27be605eec34",
    modules:['pubsub']//根据需要，传入‘pubsub’或'im’，或数组方式同时传入
});

const Index = ()=> {

    const [ message, setMessage ] = useState([])
    const [ value, setValue ] = useState("")
    const [mes,setMess] = useState([])
    const [txt,setTxt] = useState("")
    const [user,setUser] = useState({})
    const [users,setUserListMessage] = useState([
        "ezblu"
  ])

    const [mesList,setMessValue] = useState([])
    const [email,setEmail] = useState("")

     useEffect(() => {
        document.title = "EZblu客服"
        // async function kuItem(){
        //    await startOnclick() // 启动链接
        //    await getMessage();  //接受
        // }
        // kuItem()
        //setInterval(()=>{
            startOnclick()
            getMessage();
        //},1000)
        
    },[mes,email])
    
    //断开链接
    function clearOnclick(){
         //断开连接
        goeasy.disconnect({
            onSuccess: function(){
                console.log("断开链接成功")
            },
            onFailed: function(error){
                console.log("Failed to disconnect GoEasy, code:"+error.code+ ",error:"+error.content);
            }
        });
    }

    //启动链接
    function startOnclick(){
        //建立连接
        goeasy.connect({
            id:"001", //pubsub选填，im必填
            data:{"avatar":"/www/xxx.png","nickname":"ezblu客服......."}, //必须是一个对象，pubsub选填，im必填，用于上下线提醒和查询在线用户列表时，扩展更多的属性
            onSuccess: function () {  //连接成功
            console.log("连接成功") //连接成功
            
            },
            onFailed: function (error) { //连接失败
            console.log("连接失败 code:"+error.code+ ",error:"+error.content);
            },
            onProgress:function(attempts) { //连接或自动重连中
            console.log("自动重连中", attempts);
            }
        });
        
    }
    

    //接收消息
   async function getMessage(){
        
        var pubsub = goeasy.pubsub;
       await pubsub.subscribe({
            channel: "ezblu",//替换为您自己的channel
            onMessage: async function (message) {
                const contentUser = JSON.parse(message.content);
                const contentUsers = contentUser.name; //email.....
                //console.log("Channel:" + message.channel + " content:" + message.content); 
                 await setMess([...mes,{"msg":contentUser.message,
                 "Channel":'ezblu',"email":contentUsers,"authentication":contentUsers,
                  }])
                 await setEmail(contentUsers)

                // flitter 过滤
                let arrStr = users.filter((item:string) => item === contentUsers)
                if(arrStr.length <= 0){
                    setUserListMessage([...users,contentUsers]) 
                }
                //setUserListMessage([...users,contentUsers]) 
                console.log("接受到消息........")
                console.log(message)

                const element = [];
                for (let i = 0; i < mes.length; i++) {
       
                    //debugger
                    if(value === mes[i].email && mes[i].authentication === email){
                        element.push(mes[i]);
                    }
       
                }
                
                await setMessValue(element) 
                await onlineServiceClick(email)

                console.log(email)

            },
            onSuccess: function () {
                console.log("Channel订阅成功。");
            },
            onFailed: function (error) {
                console.log("Channel订阅失败, 错误编码：" + error.code + " 错误信息：" + error.content)
            }
        });
       await console.log("获取参数")
    }

    //发送消息
    async function sendMessages(){
        if(email !== ""){
            var pubsub = goeasy.pubsub;
           await pubsub.publish({
                channel: email,
                message: txt,
                onSuccess:async function(){
                await setMess([...mes,{"msg":txt,
                "Channel":email,"email":email,"authentication":email
                    }]) 

                    console.log("发送的内容:"+email+txt)
                    console.log(mes)

                    const element = [];
                    for (let i = 0; i < mes.length; i++) {
                        //debugger
                        if(value === mes[i].email && mes[i].authentication === email){
                            element.push(mes[i]);
                        }
                    }
                    
                   await setMessValue(element)   
                   await onlineServiceClick(email)
                    
                    //console.log(email)
                },
                onFailed: function (error) {
                    console.log("消息发送失败，错误编码："+error.code+" 错误信息："+error.content);
                }
            });
            setTxt("")
            await onlineServiceClick(email)
        }else{
            return;
        }
    }



    const [collapsed,setCollapsed] = useState(false)
    const toggleCollapsed = () => {
        
        setCollapsed(!collapsed)
      };


    const onlineServiceClick = (value:any)=>{
        console.log(value)
        console.log(email)
        setEmail(value)
         setMessValue([])
         const element = [];
         for (let i = 0; i < mes.length; i++) {
             //debugger
             if(value === mes[i].email && mes[i].authentication === email){
                 element.push(mes[i]);
             }
         }
         setMessValue(element) 
    }

    

    const onChange = (e:any) => {
        setTxt(e.target.value)
    };

        return (
            <div className="online-con" style={{display:"flex",flexDirection:"row"}}>
                <div 
                    className="onlineLeft"
                    style={{ width: 256,height:"75vh",backgroundColor:"rgb(0, 21, 41)",overflow:"scroll" }}>
                       
                        <Menu
                        defaultSelectedKeys={['1']}
                        defaultOpenKeys={['sub1']}
                        mode="inline"
                        theme="dark"
                        inlineCollapsed={collapsed}
                        >
                            {users.map((value,index)=>{
                                return (
                                
                                        <Menu.Item 
                                        onClick={()=>onlineServiceClick(value)}
                                        key={index} icon={<PieChartOutlined />}>
                                            {value}
                                        </Menu.Item>
                                
                                )
                            })}
                        </Menu>
                    </div>
                    <div className="onlineRight" style={{width:'100%',height:500,backgroundColor:"#ccc"}}>
                        <div style={{width:"100%",position:"relative"}}>
                            <div style={{textAlign:"center"}}>在线客服系统</div>
                            <div style={{width:"100%",height:500,background:"#fff",borderRadius:20,overflow:"scroll",paddingBottom:50}}>{mesList.map((v,i)=>{
                                return (
                                    <div key={i}> 
                                        <div> 
                                        {v.Channel !== "ezblu"?
                                        <div style={{marginTop:20,}}> 
                                                <div style={{width:"100%",borderRadius:40,display:"flex",flexDirection:"row"}}>
                                                    <div style={{width:40,height:40,borderRadius:40}}>
                                                        <img style={{width:"100%",height:"100%"}} src={Header}></img>
                                                    </div>

                                                    <div>
                                                            <h4 style={{color:"rgb(70, 77, 77)",fontWeight:"bold"}}>EZblu客服</h4>
                                                        <div style={{color:'rgb(115, 116, 118)',borderRadius:20,display:"flex",flexDirection:"row"}}> 
                                                            <h3 style={{padding:5,textAlign:"start",justifyContent:"start",background:"rgb(231, 234, 239)",
                                                        alignItems:"start",marginLeft:10,borderRadius:5,wordBreak:"break-word",Width:300}}><a 
                                                            style={{}}
                                                            >{v.msg}</a></h3>
                                                        </div>
                                                    </div>    
                                                </div>
                                            
                                        </div>
                                        
                                        :
                                        
                                        <div style={{width:"100%",display:"flex",flexDirection:"row",justifyContent:"flex-end",justifySelf:"flex-end",marginBottom:20}}> 
                                        <div style={{borderRadius:40,display:"flex",flexDirection:"row",justifyContent:"flex-end",justifySelf:"flex-end"}}>     
                                        <div style={{display:"flex",flexDirection:"row"}}>
                                                    <div style={{color:'rgb(115, 116, 118)',borderRadius:20,display:"flex",flexDirection:"row"}}> 
                                                        <h3 style={{padding:5,textAlign:"start",justifyContent:"start",background:"rgb(231, 234, 239)",
                                                        alignItems:"start",marginLeft:10,borderRadius:5,wordBreak:"break-word",width:300}}><a 
                                                        style={{}}
                                                        >{v.msg}</a></h3>
                                                    </div>  
                                            </div>   
                                            
                                            <div style={{width:40,height:40,borderRadius:40}}>
                                            <img style={{width:"100%",height:"100%"}} src={Kehu}></img>
                                            </div>
                                            
                                        </div>
                                    </div> 
                                    }

                                    
                                        </div>
                                    </div>
                                )
                            })}</div>
                            <div style={{display:"flex",flexDirection:"row",justifyContent:"center"}}>
                            <TextArea 
                            placeholder="请输入您的信息"
                            showCount
                            value={txt} 
                            maxLength={100} 
                            onChange={onChange}
                            style={{width:"100%"}}
                            />
                            <Button
                            style={{width:200,alignItems:"flex-end"}}
                            type="primary" onClick={sendMessages}>发送消息</Button>
                            </div> 
                         </div>
                    </div>
            </div>
    
        )
}
export default Index
